nestjs exception filter 설계하여 Known exception들을 500 에러가 아닌 statusCode로 응답 보내기
다음과 같은 PrismaClientKnownRequestError 에러가 발생했을 때 500에러가 아니라 AlreadyExists 같은 4XX 시리즈 에러로 보내게끔 하기 위하여 매번 Exception Class를 만드는 것은 너무 번거롭다. 따라서, NestJS Exception Filter를 만들어 적어도 Prisma가 일으키는 예외들을 처리할 수 있도록 하자.
{
"body": {
"title": "난이도",
"iconSvg": "<svg width=\"100\" height=\"100\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"40\" fill=\"red\" /></svg>",
"isRequired": true,
"highlight": true
},
"query": {},
"url": "/coach-form",
"ip": "::1",
"exception": {
"name": "PrismaClientKnownRequestError",
"code": "P2002",
"clientVersion": "5.0.0",
"meta": {
"target": "coachdetailkeymodels_title_key"
}
},
"message": "\nInvalid `.create()` invocation in\n/Users/choiwheatley/workspace/racketime-api/src/coach/coach-form.repository.ts:29:8\n\n 26 ).then((v) => v.order);\n 27 \n 28 return await this.prisma.coachDetailKey\n→ 29 .create(\nUnique constraint failed on the constraint: `coachdetailkeymodels_title_key`",
"error": "에러가 발생했습니다."
}